import { app, BrowserWindow, Menu } from "electron"
import { release } from "os"
import { useMain } from './hooks/useMain'
import { runServer, closeServer } from './hooks/useService'
import { ElectronLogger } from '@xmov/electron-extension'
import registerIpcEvent from "./ipc-event"

let closeFlag = false

// 去除默认菜单
Menu.setApplicationMenu(null)

// 操作系统版本过低则禁用硬件加速
if (release().startsWith("6.1")) app.disableHardwareAcceleration()

// win32 则改变当前应用的 Application User MODEl ID
if (process.platform === "win32") app.setAppUserModelId(app.getName())

// 单例锁
if (!app.requestSingleInstanceLock()) {
	app.quit()
	process.exit(0)
}

// 警用安全警告
process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true"

// 加载主窗口
app.whenReady().then(() => {
	closeServer()
		.then(() => runServer())
		.then(() => useMain())
		.catch(() => {
			ElectronLogger.error('start server error')
			app.quit()
		})

	// 主进程注册ipc事件
	registerIpcEvent()
})

/**
 * app生命周期钩子
 */
app.on("window-all-closed", () => {
	if (process.platform !== "darwin") app.quit()
})

app.on("will-quit", (e: Electron.Event) => {
	if (closeFlag) return
	e.preventDefault()
	closeServer().finally(() => {
		closeFlag = true
		app.quit()
	})
})

app.on("activate", () => {
	if (BrowserWindow.getAllWindows().length === 0) useMain()
})
